/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React, {useEffect, useState} from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  TouchableOpacity,
  Dimensions,
  ImageBackground,
  LogBox,
  Alert,
} from 'react-native';
import Orientation from 'react-native-orientation';
import {
  ExpandedRegionLayoutOptions,
  FoldedRegionLayoutOptions,
  FoldSplitContainer,
  HoverModeRegionLayoutOptions,
  PresetSplitRatio,
} from '@hadss/react_native_adaptive_layout/src';
import SampleTurboModule from '../basic/SampleTurboModule';
import Swiper from 'react-native-swiper';
import musicPlayer from '../util/index';

import {
  GestureHandlerRootView,
  GestureDetector,
  PanGestureHandler,
  Gesture,
} from '@react-native-oh-tpl/react-native-gesture-handler';

import {runOnJS} from 'react-native-reanimated';

import ImageLogo from './model/ImageLogo.tsx';
import MusicBaseInfo from './model/MusicBaseInfo.tsx';
import ExtraPage from './model/ExtraPage.tsx';
import {MusicPlayPageConstants} from '../util/constants.tsx';

function MusicPlay() {
  const [playState, setPlayState] = useState<boolean>();
  const [position, setPosition] = useState<number>(0);

  const [duration, setDuration] = useState<number>(0);
  const [title, setTitle] = useState<string>('');
  const [artist, setArtist] = useState<string>('');
  const [isHover, setIsHover] = useState<boolean>(false);
  const [isExpanded, setIsExpanded] = useState<boolean>(
    Dimensions.get('window').width >= 600,
  );
  const isWide =
    Dimensions.get('screen').height >= 900 ||
    Dimensions.get('screen').width >= 900;
  const [isLarge, setIsLarge] = useState<boolean>(
    Dimensions.get('window').width >= 800,
  );

  // 进度条
  const onHandlerStateChangeForProgress = (event: any) => {
    const newProgress = Math.max(
      0,
      Math.min(1, event.nativeEvent.x / (isWide && isLarge ? 300 : 320)),
    );
    seekTo(newProgress * 100);
    setPosition(newProgress * 100);
  };

  const onGestureEventForProgress = (event: any) => {
    const newProgress = Math.max(
      0,
      Math.min(1, event.nativeEvent.x / (isWide && isLarge ? 300 : 320)),
    );
    seekTo(newProgress * 100);
    setPosition(newProgress * 100);
  };

  useEffect(() => {
    LogBox.ignoreAllLogs();
    isWide && Orientation.lockToLandscape();
    const screenListener = Dimensions.addEventListener(
      'change',
      ({window: {width}}) => {
        if (isWide) {
          Orientation.lockToLandscape();
        } else {
          setIsExpanded(width >= 600);
          setIsLarge(width >= 800);
        }
      },
    );
    musicPlayer.onProgress((currentTime, duration) => {
      setPosition(currentTime / 1000);
      setDuration(duration / 1000);
    });
    updateTrack();
    musicPlayer.setOnTrackChange(() => {
      updateTrack();
    });
    return () => {
      screenListener.remove();
      isWide && Orientation.unlockAllOrientations();
    };
  }, [isWide]);

  const onLayout = (event: any) => {
    const {width} = event.nativeEvent.layout;
    setIsHover(width > 600);
  };

  // 切换播放状态
  const togglePlayPause = async () => {
    const state = musicPlayer.getCurrentStatus();
    state ? musicPlayer.pause() : musicPlayer.play();
    setPlayState(!state);
  };

  const skipToNext = async () => {
    musicPlayer.nextTrack();
    updateTrack();
    setPlayState(true);
  };

  const skipToPrevious = async () => {
    musicPlayer.previousTrack();
    updateTrack();
    setPlayState(true);
  };

  const updateTrack = () => {
    debugger;
    const track = musicPlayer.getCurrentTrack();
    if (track) {
      setPlayState(musicPlayer.getCurrentStatus());
      setArtist(track.artist);
      setTitle(track.title);
    }
  };

  const seekTo = (val: number) => {
    musicPlayer.setCurrentTime(val * 1000);
  };

  const formatTime = (second: number) => {
    // 计算分钟数，注意 Math.floor 会向下取整
    const minutes = Math.floor(second / 60);
    // 计算剩余的秒数，使用 % 运算符取余数
    const remainingSeconds = Math.floor(second % 60);
    // 使用字符串的 padStart 方法来确保分钟和秒数都是两位数
    // 如果数字小于 10，则在前面添加一个 0
    const formattedMinutes = minutes.toString().padStart(2, '0');
    const formattedSeconds = remainingSeconds.toString().padStart(2, '0');
    // 返回格式化的时间字符串
    return `${formattedMinutes}:${formattedSeconds}`;
  };

  const backToLast = () => {
    SampleTurboModule.pushStringToHarmony('PlayListPage', 2);
  };

  // 对应歌曲图片
  const primaryRender = () => <ImageLogo></ImageLogo>;

  const secondRender = () => (
    <View style={styles.centerStyle} onLayout={onLayout}>
      <MusicBaseInfo
        isHoverdate={isHover}
        title={title}
        artist={artist}></MusicBaseInfo>
      {/* 小屏上进度条 */}
      <View>
        <View style={styles.progressBarContainer}>
          <GestureHandlerRootView>
            <PanGestureHandler
              onGestureEvent={onGestureEventForProgress}
              onHandlerStateChange={onHandlerStateChangeForProgress}>
              <View>
                <View style={[styles.progressFill, {width: `${position}%`}]} />
              </View>
            </PanGestureHandler>
          </GestureHandlerRootView>
        </View>
      </View>
      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          width: isHover ? '93%' : '88%',
          marginTop: 5,
        }}>
        <Text style={styles.progressText}>{formatTime(position)}</Text>
        <Text style={styles.progressText}>{formatTime(duration)}</Text>
      </View>
      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          width: isHover ? '93%' : '88%',
          alignItems: 'center',
          marginTop: 20,
        }}>
        <Image
          source={require('../../../asset/repeat.svg')}
          style={styles.imageGrey}
        />
        <TouchableOpacity onPress={skipToPrevious}>
          <Image
            source={require('../../../asset/left.svg')}
            style={styles.image}
          />
        </TouchableOpacity>
        <TouchableOpacity onPress={togglePlayPause}>
          <Image
            source={
              playState
                ? require('../../../asset/pause.svg')
                : require('../../../asset/play.svg')
            }
            style={styles.imagePlay}
          />
        </TouchableOpacity>
        <TouchableOpacity onPress={skipToNext}>
          <Image
            source={require('../../../asset/forward_end_fill.svg')}
            style={styles.image}
          />
        </TouchableOpacity>
        <Image
          source={require('../../../asset/music_note_list.svg')}
          style={styles.imageGrey}
        />
      </View>
      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          width: isHover ? '93%' : '88%',
          alignItems: 'center',
          marginTop: 32,
        }}>
        <Image
          source={require('../../../asset/share_play.svg')}
          style={styles.imageGrey}
        />
        <Image
          source={require('../../../asset/bell.svg')}
          style={styles.imageGrey}
        />
        <Image
          source={require('../../../asset/arrow_down_circle.svg')}
          style={styles.imageGrey}
        />
        <Image
          source={require('../../../asset/dot.svg')}
          style={styles.imageGrey}
        />
      </View>
    </View>
  );

  const secondPadRender = () => (
    <View style={styles.centerStyle}>
      {/* 大屏上的进度条 */}
      <View style={styles.slider}>
        <GestureHandlerRootView>
          <PanGestureHandler
            onGestureEvent={onGestureEventForProgress}
            onHandlerStateChange={onHandlerStateChangeForProgress}>
            <View>
              <View style={[styles.progressFill, {width: `${position}%`}]} />
            </View>
          </PanGestureHandler>
        </GestureHandlerRootView>
      </View>
      <View style={styles.controls}>
        <Text style={styles.progressText}>{formatTime(position)}</Text>
        <Text style={styles.progressText}>{formatTime(duration)}</Text>
      </View>
      <View style={styles.container}>
        <Image
          source={require('../../../asset/repeat.svg')}
          style={styles.imageGrey}
        />
        <TouchableOpacity onPress={skipToPrevious}>
          <Image
            source={require('../../../asset/left.svg')}
            style={styles.image}
          />
        </TouchableOpacity>
        <TouchableOpacity onPress={togglePlayPause}>
          <Image
            source={
              playState
                ? require('../../../asset/pause.svg')
                : require('../../../asset/play.svg')
            }
            style={styles.imagePlay}
          />
        </TouchableOpacity>
        <TouchableOpacity onPress={skipToNext}>
          <Image
            source={require('../../../asset/forward_end_fill.svg')}
            style={styles.image}
          />
        </TouchableOpacity>
        <Image
          source={require('../../../asset/music_note_list.svg')}
          style={styles.imageGrey}
        />
      </View>
      <View style={styles.container}>
        <Image
          source={require('../../../asset/share_play.svg')}
          style={styles.imageGrey}
        />
        <Image
          source={require('../../../asset/bell.svg')}
          style={styles.imageGrey}
        />
        <Image
          source={require('../../../asset/arrow_down_circle.svg')}
          style={styles.imageGrey}
        />
        <Image
          source={require('../../../asset/dot.svg')}
          style={styles.imageGrey}
        />
      </View>
    </View>
  );
  const extraRender = () => (
    <View style={styles.extra}>
      <Text
        style={{
          marginTop: isHover ? 70 : 0,
          fontSize: 23,
          color: '#ffffff',
        }}>
        此歌曲为纯音乐，请您欣赏
      </Text>
    </View>
  );

  const extraRenderForPad = () => (
    <View style={styles.flexStyle}>
      <View style={styles.message}>
        <View>
          <Text style={styles.text}>{title}</Text>
          <Text style={styles.title}>{artist}</Text>
        </View>
      </View>

      <View style={styles.flexStyle}>
        <View style={styles.containerOut}>
          <Text
            style={{
              marginTop: isHover ? 70 : 0,
              fontSize: 23,
              color: '#ffffff',
            }}>
            此歌曲为纯音乐，请您欣赏
          </Text>
        </View>
        <View style={styles.imageGreyForPad}>
          <Image
            source={require('../../../asset/likes.svg')}
            style={styles.imageGrey}
          />
        </View>
      </View>
    </View>
  );

  // 歌词页面
  const extraPage = () => <ExtraPage title={title} artist={artist}></ExtraPage>;

  let expandedLayoutOptions: ExpandedRegionLayoutOptions = {
    isExtraRegionPerpendicular: true,
    verticalSplitRatio: PresetSplitRatio.LAYOUT_1V1,
    horizontalSplitRatio: 0.9,
  };

  let foldedRegionLayoutOptions: FoldedRegionLayoutOptions = {
    verticalSplitRatio: PresetSplitRatio.LAYOUT_1V1,
  };

  const hoverModeLayoutOptions: HoverModeRegionLayoutOptions = {
    horizontalSplitRatio: 0.66,
    showExtraRegion: true,
  };

  // 产按的提示
  const handleLongPress = () => {
    Alert.alert('无法分享');
  };
  const longPressGesture = Gesture.LongPress().onEnd(() =>
    runOnJS(handleLongPress)(),
  );
  return (
    <View style={styles.containerOut} pointerEvents="box-none">
      <ImageBackground
        source={require('../../../asset/blur.png')}
        style={styles.backGroundStyle}>
        <View style={styles.backGroundStyleInner}>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              width: isExpanded ? '95%' : '88%',
              alignItems: 'center',
              marginTop: 40,
            }}>
            <TouchableOpacity onPress={backToLast}>
              <Image
                source={require('../../../asset/down.png')}
                style={styles.imageSmall}
              />
            </TouchableOpacity>
            <GestureHandlerRootView>
              <GestureDetector gesture={longPressGesture}>
                <Image
                  source={require('../../../asset/share.svg')}
                  style={styles.imageSmall}
                />
              </GestureDetector>
            </GestureHandlerRootView>
          </View>
        </View>
        {isWide && (
          <View style={styles.flexDirectionStyle}>
            <View style={styles.padLayout}>
              <View style={styles.centerStyle}>
                {/* 图片*/}
                <ImageLogo></ImageLogo>
              </View>
              {secondPadRender()}
            </View>
            <View style={styles.flexStyle}>{extraRenderForPad()}</View>
          </View>
        )}
        {!isWide && isExpanded && (
          <FoldSplitContainer
            primary={primaryRender()}
            secondary={secondRender()}
            extra={extraRender()}
            expandedLayoutOptions={expandedLayoutOptions}
            foldedLayoutOptions={foldedRegionLayoutOptions}
            hoverModeLayoutOptions={hoverModeLayoutOptions}
          />
        )}
        {!isWide && !isExpanded && (
          <Swiper
            showsPagination={true}
            paginationStyle={styles.paginationStyle}
            loop={false}
            autoplay={false}
            dotStyle={styles.swiperDot}
            activeDotStyle={styles.activeDot}
            pagingEnabled={true}>
            <FoldSplitContainer
              primary={primaryRender()}
              secondary={secondRender()}
              extra={extraRender()}
              expandedLayoutOptions={expandedLayoutOptions}
              foldedLayoutOptions={foldedRegionLayoutOptions}
              hoverModeLayoutOptions={hoverModeLayoutOptions}
            />
            {extraPage()}
          </Swiper>
        )}
      </ImageBackground>
    </View>
  );
}

const styles = StyleSheet.create({
  title: {
    fontSize: 14,
    color: MusicPlayPageConstants.color2,
    marginTop: 3,
  },
  progressText: {
    fontSize: 10,
    color: MusicPlayPageConstants.color2,
  },
  artist: {
    fontSize: 16,
    color: '#ffffff',
    opacity: 0.4,
  },
  slider: {
    marginTop: 80,
    width: 300,
    height: 10,
    backgroundColor: MusicPlayPageConstants.color1,
    borderRadius: 5,
    position: 'relative',
  },
  controls: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: 300,
    marginTop: 5,
  },
  container: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: 300,
    alignItems: 'center',
    marginTop: 38,
  },
  message: {
    marginTop: '18%',
  },
  padLayout: {
    flex: 1,
  },
  extra: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    color: 'rgba(255, 255, 255, 0.9)',
    fontSize: 24,
    fontWeight: '700',
  },
  image: {
    width: 40,
    height: 40,
  },
  imageSmall: {
    width: 25,
    height: 25,
  },
  imageGrey: {
    width: 30,
    height: 30,
    opacity: 0.4,
  },
  imageGreyForPad: {
    marginBottom: 60,
    alignItems: 'flex-end',
    marginRight: 100,
  },
  imagePlay: {
    width: 80,
    height: 80,
  },
  paginationStyle: {
    height: 10,
    top: 50,
  },
  swiperDot: {
    backgroundColor: MusicPlayPageConstants.color1,
    width: 7,
    height: 6,
    borderRadius: 2,
    magin: 3,
  },
  activeDot: {
    backgroundColor: 'rgb(255,255,255)',
    width: 12,
    height: 6,
    borderRadius: 3,
    magin: 3,
  },
  progressBarContainer: {
    height: 10,
    width: 320,
    backgroundColor: MusicPlayPageConstants.color1,
    borderRadius: 5,
    position: 'relative',
    marginTop: 80,
  },
  progressFill: {
    height: '100%',
    backgroundColor: 'rgba(255, 255, 255, 0.8)',
    borderRadius: 5,
  },
  containerOut: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  centerStyle: {flex: 1, alignItems: 'center'},
  flexStyle: {
    flex: 1,
  },
  flexDirectionStyle: {flex: 1, flexDirection: 'row'},
  backGroundStyle: {width: '100%', height: '100%'},
  backGroundStyleInner: {
    position: 'absolute',
    width: '100%',
    alignItems: 'center',
    zIndex: 1,
  },
});

export default MusicPlay;
